<template>
  <div class="permission-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            新建权限
          </el-button>
        </div>
      </template>

      <!-- 权限树形表格 -->
      <el-table 
        :data="permissionList" 
        v-loading="loading" 
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="permissionName" label="权限名称" width="200" />
        <el-table-column prop="permissionCode" label="权限编码" width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="200" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editPermission(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="togglePermissionStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deletePermission(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限表单对话框 -->
    <el-dialog 
      v-model="permissionDialogVisible" 
      :title="isEdit ? '编辑权限' : '新建权限'"
      width="600px"
    >
      <el-form 
        ref="permissionFormRef" 
        :model="permissionForm" 
        :rules="permissionRules" 
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="permissionForm.permissionName" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input v-model="permissionForm.permissionCode" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型">
            <el-option label="模块" :value="1" />
            <el-option label="按钮" :value="2" />
            <el-option label="接口" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限路径" prop="path">
          <el-input v-model="permissionForm.path" placeholder="请输入权限路径" />
        </el-form-item>
        <el-form-item label="父级权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="permissionTreeOptions"
            :props="permissionTreeProps"
            placeholder="请选择父级权限"
            clearable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="permissionForm.description" 
            type="textarea" 
            placeholder="请输入权限描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="permissionForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="permissionForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {permissionApi} from "../api";

// 响应式数据
const loading = ref(false)
const permissionList = ref([])
const permissionDialogVisible = ref(false)
const isEdit = ref(false)

// 权限表单
const permissionFormRef = ref()
const permissionForm = reactive({
  id: null,
  permissionName: '',
  permissionCode: '',
  type: 1,
  path: '',
  description: '',
  parentId: null,
  sort: 0,
  status: 1
})

// 表单验证规则
const permissionRules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-z:]+$/, message: '权限编码只能包含小写字母和冒号', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 权限树选项
const permissionTreeOptions = computed(() => {
  return [{ id: null, permissionName: '顶级权限', children: permissionList.value }]
})

const permissionTreeProps = {
  children: 'children',
  label: 'permissionName',
  value: 'id'
}

// 生命周期
onMounted(() => {
  loadPermissionList()
})

// 加载权限列表
const loadPermissionList = async () => {
  try {
    loading.value = true
    const response = await permissionApi.getPermissionList()
    if (response.data.code === 200) {
      permissionList.value = buildTree(response.data.data)
    }
  } catch (error) {
    ElMessage.error('加载权限列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 构建树形结构
const buildTree = (data, parentId = null) => {
  return data
    .filter(item => item.parentId === parentId)
    .map(item => ({
      ...item,
      children: buildTree(data, item.id)
    }))
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type) => {
  const typeMap = {
    1: '模块',
    2: '按钮',
    3: '接口'
  }
  return typeMap[type] || '未知'
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  resetPermissionForm()
  permissionDialogVisible.value = true
}

// 编辑权限
const editPermission = (permission) => {
  isEdit.value = true
  Object.assign(permissionForm, permission)
  permissionDialogVisible.value = true
}

// 重置权限表单
const resetPermissionForm = () => {
  permissionForm.id = null
  permissionForm.permissionName = ''
  permissionForm.permissionCode = ''
  permissionForm.type = 1
  permissionForm.path = ''
  permissionForm.description = ''
  permissionForm.parentId = null
  permissionForm.sort = 0
  permissionForm.status = 1
  permissionFormRef.value?.resetFields()
}

// 保存权限
const savePermission = async () => {
  try {
    await permissionFormRef.value.validate()
    
    if (isEdit.value) {
      const response = await permissionApi.updatePermission(permissionForm.id, permissionForm)
      if (response.data.code === 200) {
        ElMessage.success('权限更新成功')
        permissionDialogVisible.value = false
        loadPermissionList()
      }
    } else {
      const response = await permissionApi.createPermission(permissionForm)
      if (response.data.code === 200) {
        ElMessage.success('权限创建成功')
        permissionDialogVisible.value = false
        loadPermissionList()
      }
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
    console.error(error)
  }
}

// 删除权限
const deletePermission = async (permission) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限"${permission.permissionName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await permissionApi.deletePermission(permission.id)
    if (response.data.code === 200) {
      ElMessage.success('权限删除成功')
      loadPermissionList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 切换权限状态
const togglePermissionStatus = async (permission) => {
  try {
    const newStatus = permission.status === 1 ? 0 : 1
    const response = await permissionApi.updatePermissionStatus(permission.id, newStatus)
    if (response.data.code === 200) {
      ElMessage.success('状态更新成功')
      loadPermissionList()
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    console.error(error)
  }
}
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
